import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:http/http.dart' as http;
import 'package:netstorage/model/login_data.dart';
import 'package:netstorage/model/response_result.dart';
import 'package:netstorage/utils/navigator_utils.dart';

class LoginDao {
  static const boardingPass = 'boarding_pass';
  static const url = 'https://xdfznh.club/zknoteb/user/login/email/password';

  //#region 登录
  static Future<bool> login({required String username, required String password}) async {
    Map<String,String> reqData = {'email':'chanchaw@126.com','password':'eVF4TJ'};
    var uri = Uri.parse(url);
    var res = await http.post(
      uri,
      body: jsonEncode(reqData),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8', // 关键：设置 Content-Type
      },
    );

    // http请求异常
    if(res.statusCode != 200) {
      String errMsg = '登录出现异常：\ncode:${res.statusCode},msg:${res.body}';
      // print(errMsg);
      throw Exception(errMsg);
    }

    // 请求成功的话 res.body:
    // {"success":true,"msg":"登录成功","data":{"userToken":"userToken:dafd9a6ee74c40c399235bcb5dbe71cd","user":{"id":8,"email":"chanchaw@126.com","nickname":"爱思考的飞飞","headPic":"https://cdn.vuetifyjs.com/images/john.jpg","level":0,"time":"2023-05-05 15:03:33","status":1}}}

    // 处理中文，将响应结果转换为 ResponseResult 对象
    Utf8Decoder utf8decoder = const Utf8Decoder();
    String bodyString = utf8decoder.convert(res.bodyBytes);
    var resMap = jsonDecode(bodyString);
    var resEntity = ResponseResult.fromJson(resMap);

    // 后台响应不成功
    bool success = resEntity.success ?? true;
    if(!success) throw Exception(resEntity.msg ?? '登录失败！');

    LoginData loginData = LoginData.fromJson(resEntity.data);

    // 缓存 token
    _saveToken(loginData.userToken ?? '');

    String t1 = getToken();
    print('从缓存中获取到的token:$t1');
    return true;
  }
  //#endregion

  //#region 缓存token
  static void _saveToken(String token){
    HiCache.getInstance().setString('userToken', token ?? '');
  }

  static String getToken(){
    return HiCache.getInstance().get('userToken') ?? '';
  }
  //#endregion

  //#region 注销退出
  static void logout(){
    // 移除保存的token
    HiCache.getInstance().remove('userToken');
    String aa = HiCache.getInstance().get('userToken') ?? '';
    print('logout 后再次获取的 userToken:$aa');
  }
  //#endregion
}
